<?php
/*
+------------------------------------------------------------------------------+
| Copyright (c) 2009, Draftrack Team                                           |
| All rights reserved.                                                         |
|                                                                              |
| Redistribution and use in source and binary forms, with or without           |
| modification, are permitted provided that the following conditions are met:  |
|     * Redistributions of source code must retain the above copyright         |
|       notice, this list of conditions and the following disclaimer.          |
|     * Redistributions in binary form must reproduce the above copyright      |
|       notice, this list of conditions and the following disclaimer in the    |
|       documentation and/or other materials provided with the distribution.   |
|     * Neither the name of the <organization> nor the                         |
|       names of its contributors may be used to endorse or promote products   |
|       derived from this software without specific prior written permission.  |
|                                                                              |
| THIS SOFTWARE IS PROVIDED BY draftrack team ''AS IS'' AND ANY                |
| EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED    |
| WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE       |
| DISCLAIMED. IN NO EVENT SHALL draftrack team BE LIABLE FOR ANY               |
| DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES   |
| (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND  |
| ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS|
| SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                 |
+------------------------------------------------------------------------------+

 * @category   Zend_extension
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action
*/

class IndexController extends Zend_Controller_Action
{
    function init()
    {
    	
    }

    function indexAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	
		$dataStore = new Myzen_Oauth_Datastore_Db();
		$server = new Myzen_Oauth_Server($dataStore);
		$hmac_method = new Myzen_Oauth_Signaturemethod_HMACSHA1();
		$server->add_signature_method($hmac_method);
		
		$consumer = $dataStore->lookup_consumer('consumerkey');
		print_r($consumer);
		$dataStore->new_request_token($consumer);
    	    
    }
    
    function requesttokenAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	
		$dataStore = new Myzen_Oauth_Datastore_Db();
		$server = new Myzen_Oauth_Server($dataStore);
		$hmac_method = new Myzen_Oauth_Signaturemethod_HMACSHA1();
		$server->add_signature_method($hmac_method); 
		
	try {
  		$req = Myzen_Oauth_Request::from_request();	

Zend_Registry::get('dt_log')->log('request token data:'.serialize($req), Zend_Log::DEBUG);
		
  		$token = $server->fetch_request_token($req);

Zend_Registry::get('dt_log')->log('request token:'.serialize($token), Zend_Log::DEBUG);

  		echo $token;
	} catch (Myzen_Oauth_Exception $e) {
  		header('HTTP/1.0 401 Unauthorized'); 
  		echo $e->getMessage();
	}
		    
    
  }
  
  
  	//action called by cron to clean the nounces every 5 minutes
	function cleannounceAction() {
		$this->getHelper('viewRenderer')->setNoRender();
		//we clean the nounces
		$dataStore = new Myzen_Oauth_Datastore_Db();
		$nbNounces = $dataStore->cleanup_nounce();
Zend_Registry::get('dt_log')->log('nb nounces deleted:'.$nbNounces, Zend_Log::INFO);
		
		$data['status'] = 	'OK';
		$data['nbNounces'] = $nbNounces;
		echo Zend_Registry::get('dt_serializer')->serialize($data);				
		return;
	} //end cleannounce
	
	

    function identifyAction()
    {
		//before displaying the form we check that we knows the token

		$dataStore = new Myzen_Oauth_Datastore_Db();
		$server = new Myzen_Oauth_Server($dataStore);
		$hmac_method = new Myzen_Oauth_Signaturemethod_HMACSHA1();
		$server->add_signature_method($hmac_method); 

		$requestToken = $this->_getParam('oauth_token');

Zend_Registry::get('dt_log')->log('validate request token data:'.serialize($requestToken), Zend_Log::DEBUG);
		
		$validToken = $dataStore->lookup_token(null,'request', $requestToken);

Zend_Registry::get('dt_log')->log('answer of the token datastore:'.serialize($validToken), Zend_Log::DEBUG);

		
		if(!is_object($validToken)) {
			echo $requestToken.' Request token not recognized, please go back to the consumer and try again';
			exit;
		}
		
		$this->view->requestToken = $requestToken;
		
    }
    
    function completeauthfromexternalproviderAction() {
		$authDetails = $this->view->authDetails;

		if(!Myzen_Utilities_UserDetails::isSignatureValid($authDetails)) {
			$this->view->messageDisplay('An issue occured while identifying you, please retry later','error');
			$this->_redirect($this->view->baseUrl().'/auth/login/signup/');
			return;		
		} //end signature not valid
	
		//we check if the user is known
		$email = $authDetails['user']['email'];
		
		//Password is generated based on secret
		$password = Zend_Registry::get('dt_config')->auth->password->pre.$email.Zend_Registry::get('dt_config')->auth->password->post;
		
		//We check that the user already exists or not
		$authAdapter = new Myzen_Auth_Adapter_DbTable($email,$password);
		$authResult = $authAdapter->authenticate();
		
		
		
		if (!$authResult->isValid()) {
			//User is not already existsing, we create an account for him
			
			$split = preg_split('/@/',$email);
			$pseudo = $split[0];
			
			$db = Zend_Registry::get('dt_dbs')->getDb('user','details','key');
			$dbData = array(
				'email' => $email,
				'password' => sha1($password),
				'pseudo' => $pseudo
			);
			$db->insert('userCredential',$dbData);
			Zend_Registry::get('dt_log')->log('creating account for user '.$email, Zend_Log::INFO);
		}
		$this->_setParam('email',$email);
		$this->_setParam('password',$password);
		
		//We forward to the request access
    	$this->_forward('requestaccess');
    } //end completeauthfromexternalprovider
    
    
    

    function requestaccessAction()
    {

		//check if the user is authenticated
		$email = $this->_getParam('email');
		$password = $this->_getParam('password');
		
		$requestToken = $this->_getParam('oauth_token');		

				
		$authAdapter = new Myzen_Auth_Adapter_DbTable($email,$password);
		$authResult = $authAdapter->authenticate();
		
		if (!$authResult->isValid()) {
			echo 'user not found';
			$this->_forward('identify');
			return;	
		}
		
		//OK the user is authenticated we ask if he/she wants to grant access to the application 
		$dataStore = new Myzen_Oauth_Datastore_Db();
		$consumer = $dataStore->getConsumerFromToken('request', $requestToken);
		
		$this->view->email =$email;
		$this->view->password = $password;
		$this->view->requestToken = $requestToken;
		$this->view->consumerName = $consumer->name;		
		
		//We don t grant for the time being, grant is automatically agreed
		$this->_forward('grantaccess'); 
    
    }

    function grantaccessAction()
    {

		$deny = $this->_getParam('deny');
		if(isset($deny) && '1' == $deny) {
			$this->_redirect('http://www.google.com');
			return;	
		}
		
		//check if the user is authenticated
		$email = $this->_getParam('email');
		$password = $this->_getParam('password');
		

		$requestToken = $this->_getParam('oauth_token');
	
		
		$authAdapter = new Myzen_Auth_Adapter_DbTable($email,$password);
		$authResult = $authAdapter->authenticate();
		
		if (!$authResult->isValid()) {
			$this->_forward('identify');
			return;	
		}
		
		
		//OK we need to authorize the token
		$dataStore = new Myzen_Oauth_Datastore_Db();
		$token = $dataStore->lookup_token(null,'request',$requestToken);
		$consumer = $dataStore->getConsumerFromToken('request', $requestToken);
		$token->authorize($email);

Zend_Registry::get('dt_log')->log('Request token has been authorised:'.$token, Zend_Log::DEBUG);

		
		$consumer->getCallbackURL();

Zend_Registry::get('dt_log')->log('Redirection to:'.$consumer->getCallbackURL().'?'.$token->toGrantDetails(), Zend_Log::DEBUG);
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->_redirect($consumer->getCallbackURL().'?'.$token->toGrantDetails());
      
    
    }

  function accesstokenAction() {
    $this->getHelper('viewRenderer')->setNoRender();
	$dataStore = new Myzen_Oauth_Datastore_Db();
	$server = new Myzen_Oauth_Server($dataStore);
	$hmac_method = new Myzen_Oauth_Signaturemethod_HMACSHA1();
	$server->add_signature_method($hmac_method);

    try {
  	  $req = Myzen_Oauth_Request::from_request();
 
 Zend_Registry::get('dt_log')->log('Front end try to get access token:'.serialize($req), Zend_Log::DEBUG);


	  $accessToken = $server->fetch_access_token($req);

Zend_Registry::get('dt_log')->log('Access token provided:'.$accessToken, Zend_Log::DEBUG);
	  

	  echo $accessToken;
      die();      
    } catch (OAuthException $e) {
  	  header('HTTP/1.0 401 Unauthorized');
      print($e->getMessage() . "\n<hr />\n");
      print_r($req);
      die();
    }      
  }

}


?>